package dev.spb3.controller;

import dev.spb3.model.Book;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/books")
public class RestBookController {
    private List<Book> books = new ArrayList<>(
            List.of(new Book("The Great Gatsby", "Tom"),
                    new Book("Moby Dick", "Jim"),
                    new Book("War and Peace", "David")));
    @GetMapping
    @Operation(summary = "获取所有书籍", description = "获取所有书籍")
    public ResponseEntity<List<Book>> getBooks() {
        return ResponseEntity.ok(books);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Book> getBookById(@PathVariable Long id) {
        return ResponseEntity.ok(books.get(id.intValue()));
    }

    @PostMapping
    public ResponseEntity<Book> createBook(@RequestBody Book book) {
        books.add(book);
        return ResponseEntity.ok(book);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Book> updateBook(@PathVariable Long id, @RequestBody Book book) {
        Book book1 = books.get(id.intValue());
        BeanUtils.copyProperties(book, book1);
        books.add(id.intValue(), book1);
        return ResponseEntity.ok(book1);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Book> deleteBook(@PathVariable Long id) {
        Book book = books.get(id.intValue());
        books.remove(id.intValue());
        return ResponseEntity.ok(book);
    }
}
